package com.km.wskj.itmonitor.pager.monitor.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.App;
import com.km.wskj.itmonitor.model.MyChartData;
import com.km.wskj.itmonitor.pager.base.LFragment;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * @author by Xianling.Zhou on 2017/2/28.
 */
//应用系统运行状态
public class AppRunStateFragment extends LFragment {

    private static final String TAG = "AppRunStateFragment";

    @BindView(R.id.app_run_state_barchart)
    BarChart mBarChart;

    private List<MyChartData> data;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater
            , @Nullable ViewGroup container
            , @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_app_run_state, container, false);
        ButterKnife.bind(this, view);
        initData();

        return view;
    }

    private void initData() {
        /**
         * 初始化动作
         */
        mBarChart.getDescription().setEnabled(false);
        mBarChart.setMaxVisibleValueCount(60);
        mBarChart.setPinchZoom(false);
        mBarChart.setDrawBarShadow(false);
        mBarChart.setDrawGridBackground(false);

        final XAxis xAxis = mBarChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f);
        xAxis.setLabelCount(10);

        /**
         * Y轴默认显示左右两个轴线
         */
        YAxis rightAxis = mBarChart.getAxisRight();  //获取右边的轴线
        rightAxis.setEnabled(true); //设置图表右边的y轴禁用
        rightAxis.enableGridDashedLine(10f, 10f, 0f);
        rightAxis.setDrawLabels(false);
        rightAxis.setDrawAxisLine(false);

        YAxis axisLeft = mBarChart.getAxisLeft();
        axisLeft.setDrawGridLines(false);
        axisLeft.setLabelCount(6);
        axisLeft.setAxisMinimum(0f);
        axisLeft.setAxisMaximum(100f);


        mBarChart.animateY(2500);
        mBarChart.getLegend().setEnabled(false);

        /**
         * 请求数据
         */
        pdc.appList(HTTP_TASK_TAG, new ZxlGenericsCallback<List<App>>() {

            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
            }

            @Override
            public void onResponse(List<App> apps, int i) {
                // 这是你要绘制的原始数据
                data = new ArrayList<>();
                for (int j = 0; j < apps.size(); j++) {
                    data.add(new MyChartData((float) j, 100f, apps.get(j).appSortName));
                }
                //x轴线坐标
                xAxis.setValueFormatter(new IAxisValueFormatter() {
                    @Override
                    public String getFormattedValue(float value, AxisBase axis) {
                        return data.get(Math.min(Math.max((int) value, 0), data.size() - 1)).xAxisValue;
                    }
                });

                ArrayList<BarEntry> values = new ArrayList<BarEntry>();
                List<Integer> colors = new ArrayList<Integer>();

                int green = Color.rgb(100, 203, 107);
                int red = Color.rgb(250, 89, 68);

                for (int k = 0; k < data.size(); k++) {
                    MyChartData d = data.get(k);
                    BarEntry entry = new BarEntry(d.xValue, d.yValue);
                    values.add(entry);

                    //运行状态
                    if (apps.get(k).isAlive)
                        colors.add(green);
                    else
                        colors.add(red);

                }

                BarDataSet set;

                if (mBarChart.getData() != null &&
                        mBarChart.getData().getDataSetCount() > 0) {

                    set = (BarDataSet) mBarChart.getData().getDataSetByIndex(0);
                    set.setValues(values);
                    mBarChart.getData().notifyDataChanged();
                    mBarChart.notifyDataSetChanged();

                } else {
                    set = new BarDataSet(values, "Values");
                    set.setColors(colors);
                    set.setValueTextColors(colors);

                    BarData data = new BarData(set);
                    data.setValueTextSize(10f);
                    data.setValueFormatter(new ValueFormatter());
                    data.setBarWidth(0.5f);

                    mBarChart.setData(data);
                    mBarChart.invalidate();
                }
            }
        });
    }


    private class ValueFormatter implements IValueFormatter {

        private DecimalFormat mFormat;

        public ValueFormatter() {
            mFormat = new DecimalFormat("######.0");
        }

        @Override
        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
            return mFormat.format(value);
        }
    }
}
